<template>
	<view class="content">
		<image class="logo" src="/static/logo.png" @click="jumpAppPay"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
			<text class="subtitle">点击Logo进入专业测试页面</text>
		</view>
		
		<!-- 支付区域 -->
		<view class="pay-section">
			<view class="pay-info">
				<text class="pay-title">微信App支付测试</text>
				<view class="pay-item">
					<text class="label">商品名称：</text>
					<input v-model="orderData.body" placeholder="请输入商品名称" class="input" />
				</view>
				<view class="pay-item">
					<text class="label">支付金额：</text>
					<view class="amount-input">
						<input v-model="orderData.total_fee" placeholder="请输入金额(分)" class="input" type="number" />
						<text class="amount-tip">{{formatAmount(orderData.total_fee)}}</text>
					</view>
				</view>
				<view class="pay-item">
					<text class="label">订单号：</text>
					<view class="order-input">
						<input v-model="orderData.out_trade_no" placeholder="自动生成" class="input" disabled />
						<button @click="generateNewOrderNo" class="refresh-btn">刷新</button>
					</view>
				</view>
			</view>
			
			<!-- 操作按钮 -->
			<view class="action-buttons">
				<button @click="generateSignOnly" class="btn btn-secondary" :disabled="isLoading">
					仅生成签名
				</button>
				<button @click="startAppPay" class="btn btn-primary" :disabled="isLoading">
					{{isLoading ? '处理中...' : '开始支付'}}
				</button>
			</view>
			
			<!-- 状态显示 -->
			<view class="status-section" v-if="statusMessage">
				<view class="status-item" :class="statusType">
					<text class="status-text">{{statusMessage}}</text>
				</view>
			</view>
			
			<!-- 签名信息显示 -->
			<view class="sign-section" v-if="signResult">
				<text class="section-title">签名信息</text>
				<view class="sign-item">
					<text class="sign-label">类型：</text>
					<text class="sign-value">{{signResult.type}}</text>
				</view>
				<view class="sign-item">
					<text class="sign-label">签名：</text>
					<text class="sign-value sign-hash">{{signResult.sign}}</text>
				</view>
				<view class="sign-item">
					<text class="sign-label">签名字符串：</text>
					<text class="sign-value sign-string">{{signResult.signString}}</text>
				</view>
			</view>
			
			<!-- 调试信息 -->
			<view class="debug-section" v-if="debugInfo">
				<text class="debug-title">调试信息</text>
				<text class="debug-text">{{debugInfo}}</text>
			</view>
		</view>
	</view>
</template>

<script>
import { WxPayUtil } from '../../utils/wxpay.js'

export default {
	data() {
		return {
			title: '微信支付Demo',
			isLoading: false,
			debugInfo: '',
			statusMessage: '',
			statusType: 'info',
			signResult: null,
			
			// 使用新的WxPayUtil实例
			wxPayUtil: null,
			
			orderData: {
				body: 'App支付测试商品',
				total_fee: 1, // 单位：分
				out_trade_no: '',
				spbill_create_ip: '127.0.0.1'
			}
		}
	},
	
	onLoad() {
		// 初始化微信支付工具
		this.wxPayUtil = new WxPayUtil({
			appid: 'wxe281b4ec4c2ae13c',
			mch_id: '1700381946',
			key: '79c16a13e46c56bc73d937cc5ac552ec',
			notify_url: 'https://api.aibaxing.com/server/api/wxPay/payNotify'
		})
		
		// 生成初始订单号
		this.generateNewOrderNo()
		
		this.showStatus('页面加载完成，可以开始测试支付', 'success')
	},
	
	methods: {
		// 格式化金额显示
		formatAmount(amount) {
			if (!amount || amount <= 0) return ''
			const yuan = (amount / 100).toFixed(2)
			return `(${yuan}元)`
		},
		
		// 生成新订单号
		generateNewOrderNo() {
			this.orderData.out_trade_no = this.wxPayUtil.generateOrderNo('APP')
			this.showStatus('订单号已生成', 'info')
		},
		
		// 仅生成签名（用于测试）
		generateSignOnly() {
			try {
				if (!this.validateOrderData()) return
				
				// 生成统一下单签名
				const unifiedOrderResult = this.wxPayUtil.prepareUnifiedOrderParams(this.orderData)
				
				this.signResult = {
					type: '统一下单签名',
					sign: unifiedOrderResult.signInfo.sign,
					signString: unifiedOrderResult.signInfo.signString
				}
				
				this.debugInfo = `【统一下单参数】\n${JSON.stringify(unifiedOrderResult.params, null, 2)}\n\n【签名信息】\n签名字符串: ${unifiedOrderResult.signInfo.signString}\n最终签名: ${unifiedOrderResult.signInfo.sign}`
				
				this.showStatus('统一下单签名生成成功', 'success')
				
			} catch (error) {
				this.showStatus('签名生成失败: ' + error.message, 'error')
				console.error('签名生成失败:', error)
			}
		},
		
		// 开始App支付流程
		async startAppPay() {
			if (!this.validateOrderData()) return
			
			this.isLoading = true
			this.debugInfo = ''
			this.signResult = null
			
			try {
				this.showStatus('开始App支付流程...', 'info')
				
				// 调用完整的App支付流程
				const result = await this.wxPayUtil.startAppPay(this.orderData)
				
				if (result.success) {
					this.showStatus('支付流程执行成功', 'success')
					this.debugInfo = `【支付成功】\n订单号: ${result.orderNo}\n支付结果: ${JSON.stringify(result.payResult, null, 2)}`
					
					// 生成新订单号供下次使用
					this.generateNewOrderNo()
					
				} else {
					throw new Error(result.message || '支付失败')
				}
				
			} catch (error) {
				console.error('App支付流程失败:', error)
				this.showStatus('支付失败: ' + error.message, 'error')
				
				// 显示详细错误信息
				if (error.error) {
					this.debugInfo = `【错误详情】\n${JSON.stringify(error.error, null, 2)}`
				} else {
					this.debugInfo = `【错误信息】\n${error.message}`
				}
				
				// 如果是环境不支持的错误，提供解决方案
				if (error.message && error.message.includes('当前环境不支持')) {
					this.debugInfo += '\n\n【解决方案】\n1. 在HBuilderX中打包为App\n2. 安装到真机上测试\n3. 或使用模拟器测试App支付功能'
				}
			} finally {
				this.isLoading = false
			}
		},
		
		// 验证订单数据
		validateOrderData() {
			if (!this.orderData.body || this.orderData.body.trim() === '') {
				this.showStatus('请输入商品名称', 'warning')
				return false
			}
			
			if (!this.orderData.total_fee || this.orderData.total_fee <= 0) {
				this.showStatus('请输入有效的支付金额', 'warning')
				return false
			}
			
			if (!this.orderData.out_trade_no) {
				this.generateNewOrderNo()
			}
			
			return true
		},
		
		// 显示状态信息
		showStatus(message, type = 'info') {
			this.statusMessage = message
			this.statusType = type
			
			// 3秒后自动隐藏
			setTimeout(() => {
				this.statusMessage = ''
			}, 3000)
		},
		
		// 跳转到专业测试页面
		jumpAppPay() {
			uni.navigateTo({
				url: '/pages/app-pay/app-pay'
			})
		}
	}
}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-start;
		padding: 20rpx;
		min-height: 100vh;
		background: #f5f5f5;
	}

	.logo {
		height: 120rpx;
		width: 120rpx;
		margin: 40rpx auto;
		border-radius: 60rpx;
		box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
	}

	.text-area {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.title {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 10rpx;
	}
	
	.subtitle {
		font-size: 24rpx;
		color: #666;
	}
	
	.pay-section {
		width: 100%;
		max-width: 600rpx;
	}
	
	.pay-info {
		background: #fff;
		padding: 40rpx;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
		margin-bottom: 30rpx;
	}
	
	.pay-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 40rpx;
		text-align: center;
	}
	
	.pay-item {
		display: flex;
		align-items: flex-start;
		margin-bottom: 30rpx;
	}
	
	.label {
		font-size: 28rpx;
		color: #666;
		width: 160rpx;
		flex-shrink: 0;
		margin-top: 15rpx;
	}
	
	.input {
		flex: 1;
		height: 70rpx;
		border: 2rpx solid #e5e5e5;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}
	
	.input:disabled {
		background-color: #f5f5f5;
		color: #999;
	}
	
	.amount-input {
		flex: 1;
		display: flex;
		flex-direction: column;
	}
	
	.amount-tip {
		font-size: 22rpx;
		color: #06ad56;
		margin-top: 5rpx;
		margin-left: 20rpx;
	}
	
	.order-input {
		flex: 1;
		display: flex;
		align-items: center;
	}
	
	.refresh-btn {
		margin-left: 15rpx;
		padding: 15rpx 25rpx;
		background: #f0f0f0;
		border: none;
		border-radius: 35rpx;
		font-size: 24rpx;
		color: #666;
	}
	
	.action-buttons {
		display: flex;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}
	
	.btn {
		flex: 1;
		height: 90rpx;
		border: none;
		border-radius: 45rpx;
		font-size: 32rpx;
		font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
	}
	
	.btn-primary {
		background: linear-gradient(135deg, #07c160 0%, #06ad56 100%);
	}
	
	.btn-secondary {
		background: linear-gradient(135deg, #6c757d 0%, #545b62 100%);
	}
	
	.btn:disabled {
		background: #ccc !important;
	}
	
	.status-section {
		margin-bottom: 30rpx;
	}
	
	.status-item {
		padding: 20rpx 30rpx;
		border-radius: 10rpx;
		text-align: center;
	}
	
	.status-item.success {
		background: #e8f5e8;
		border: 1rpx solid #06ad56;
	}
	
	.status-item.error {
		background: #ffeaea;
		border: 1rpx solid #ff5722;
	}
	
	.status-item.warning {
		background: #fff8e1;
		border: 1rpx solid #ff9800;
	}
	
	.status-item.info {
		background: #e3f2fd;
		border: 1rpx solid #2196f3;
	}
	
	.status-text {
		font-size: 26rpx;
		color: #333;
	}
	
	.sign-section {
		background: #fff;
		padding: 30rpx;
		border-radius: 15rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.section-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}
	
	.sign-item {
		margin-bottom: 15rpx;
	}
	
	.sign-label {
		font-size: 24rpx;
		color: #666;
		display: block;
		margin-bottom: 5rpx;
	}
	
	.sign-value {
		font-size: 22rpx;
		color: #333;
		word-break: break-all;
		line-height: 1.4;
	}
	
	.sign-hash {
		color: #06ad56;
		font-weight: bold;
		font-family: monospace;
	}
	
	.sign-string {
		color: #666;
		font-family: monospace;
	}
	
	.debug-section {
		background: #f8f8f8;
		padding: 30rpx;
		border-radius: 10rpx;
		border: 1rpx solid #e5e5e5;
	}
	
	.debug-title {
		font-size: 24rpx;
		color: #666;
		font-weight: bold;
		display: block;
		margin-bottom: 20rpx;
	}
	
	.debug-text {
		font-size: 20rpx;
		color: #999;
		word-break: break-all;
		line-height: 1.6;
		white-space: pre-wrap;
		font-family: monospace;
	}
</style>
